<template>
  <div class="container">
    <h1>已审批故障报修单列表</h1>

    <!-- 已审批报修单表格 -->
    <table v-if="Array.isArray(repairList) && repairList.length > 0" class="repair-table">
      <thead>
      <tr>
        <th>报修ID</th>
        <th>用户姓名</th>
        <th>类型</th>
        <th>标题</th>
        <th>报修时间</th>
        <th>状态</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="repair in repairList" :key="repair.failureRepairId">
        <td>{{ repair.failureRepairId }}</td>
        <td>{{ repair.fullName }}</td>
        <td>{{ repair.type }}</td>
        <td>{{ repair.title }}</td>
        <td>{{ repair.repairTime }}</td>
        <td>{{ repair.repairStatus }}</td>
        <td>
          <button @click="openCreateTaskModal(repair.failureRepairId, repair)">创建维修任务</button>
        </td>
      </tr>
      </tbody>
    </table>
    <p v-else>暂无已审批报修记录。</p>

    <!-- 维修人员表格 -->
    <table v-if="Array.isArray(repairPersonnelList) && repairPersonnelList.length > 0" class="personnel-table">
      <thead>
      <tr>
        <th>维修人员ID</th>
        <th>姓名</th>
        <th>性别</th>
        <th>维护类型</th>
        <th>本月任务量</th>
        <th>每月任务指标</th>
        <th>已完成任务总量</th>
        <th>忙碌状态</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="personnel in repairPersonnelList" :key="personnel.repairPersonnelId">
        <td>{{ personnel.repairPersonnelId }}</td>
        <td>{{ personnel.fullName }}</td>
        <td>{{ personnel.gender }}</td>
        <td>{{ personnel.maintenanceType }}</td>
        <td>{{ personnel.monthlyTaskCount }}</td>
        <td>{{ personnel.monthlyTaskTarget }}</td>
        <td>{{ personnel.totalTaskCount }}</td>
        <td>{{ personnel.busyStatus }}</td>
      </tr>
      </tbody>
    </table>
    <p v-else>暂无维修人员记录。</p>

    <!-- 创建任务模态框 -->
    <div v-if="showCreateTaskModal" class="modal">
      <div class="modal-content">
        <span class="close" @click="closeCreateTaskModal">&times;</span>
        <h2>创建维修任务</h2>
        <form @submit.prevent="createRepairTask">
          <div>
            <label for="repairPersonnelId">选择维修人员:</label>
            <select v-model="selectedRepairPersonnelId" id="repairPersonnelId" required>
              <option v-for="personnel in repairPersonnelList" :key="personnel.repairPersonnelId" :value="personnel.repairPersonnelId">
                {{ personnel.fullName }}
              </option>
            </select>
          </div>
          <input type="hidden" v-model="selectedFailureRepairId" />
          <button type="submit">创建任务</button>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';

const repairList = ref<any[]>([]);
const repairPersonnelList = ref<any[]>([]);
const showCreateTaskModal = ref(false);
const selectedFailureRepairId = ref<number | null>(null);
const selectedRepair = ref<any>(null); // 用于存储选中的报修单信息
const selectedRepairPersonnelId = ref<number | null>(null);

const fetchApprovedRepairs = async () => {
  try {
    const response = await axios.get('http://localhost:8001/failure-repair1/approved');
    console.log('已审批报修单数据:', response.data); // 调试输出
    if (response.data && Array.isArray(response.data)) {
      repairList.value = response.data;
    } else {
      repairList.value = [];
    }
  } catch (error) {
    console.error('获取已审批报修单时出错:', error);
    repairList.value = [];
  }
};

// 获取维修人员信息
const fetchRepairPersonnel = async () => {
  try {
    const response = await axios.get('http://localhost:8001/repair-personnel1/list');
    if (response.data && Array.isArray(response.data)) {
      repairPersonnelList.value = response.data;
    } else {
      repairPersonnelList.value = [];
    }
  } catch (error) {
    console.error('获取维修人员信息时出错:', error);
    repairPersonnelList.value = [];
  }
};

onMounted(() => {
  console.log('组件挂载，获取已审批报修单');
  fetchApprovedRepairs();
  fetchRepairPersonnel();
});

// 打开创建任务模态框
const openCreateTaskModal = (failureRepairId: number, repair: any) => {
  selectedFailureRepairId.value = failureRepairId;
  selectedRepair.value = repair; // 存储选中的报修单信息
  showCreateTaskModal.value = true;
};

// 关闭创建任务模态框
const closeCreateTaskModal = () => {
  showCreateTaskModal.value = false;
  selectedFailureRepairId.value = null;
  selectedRepair.value = null;
  selectedRepairPersonnelId.value = null;
};

// 创建维修任务
const createRepairTask = async () => {
  if (selectedFailureRepairId.value === null || selectedRepairPersonnelId.value === null) {
    alert('请填写所有必填项');
    return;
  }

  try {
    // 检查是否已存在任务
    const checkResponse = await axios.get(`http://localhost:8001/repair-tasks1/exists/${selectedFailureRepairId.value}`);
    if (checkResponse.data) {
      alert('该报修单已存在任务');
      return;
    }

    // 创建新任务
    const task = {
      failureRepairId: selectedFailureRepairId.value,
      repairPersonnelId: selectedRepairPersonnelId.value,
      assignedTime: new Date().toISOString()
    };
    const response = await axios.post('http://localhost:8001/repair-tasks1', task);
    if (response.status === 200) {
      // 添加到 maintenance_records 表
      const maintenanceRecord = {
        userNo: selectedRepair.value.userNo,
        fullName: selectedRepair.value.fullName,
        type: selectedRepair.value.type,
        title: selectedRepair.value.title,
        repairTime: selectedRepair.value.repairTime,
        contactNumber: selectedRepair.value.contactNumber,
        repairAddress: selectedRepair.value.repairAddress,
        faultDescription: selectedRepair.value.faultDescription,
        employeeId: selectedRepairPersonnelId.value,
        employeeName: repairPersonnelList.value.find(personnel => personnel.repairPersonnelId === selectedRepairPersonnelId.value)?.fullName || '',
        dispatchTime: new Date().toISOString(),
        maintenanceStatus: '进行中', // 你可以根据实际情况调整
        recordTime: new Date().toISOString(),
        repairDetails: '',
        createTime: new Date().toISOString(),
        evaStatus: '待评价'
      };
      await axios.post('http://localhost:8003/maintenance-records/upBackData', maintenanceRecord);

      // 从本地列表中移除已创建的任务
      repairList.value = repairList.value.filter(repair => repair.failureRepairId !== selectedFailureRepairId.value);

      alert('任务创建成功');
      closeCreateTaskModal();
    } else {
      alert('任务创建失败');
    }
  } catch (error) {
    console.error('创建任务时出错:', error);
    alert('任务创建失败');
  }
};
</script>

<style scoped>
/* 样式优化 */
.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center;
}

th {
  background-color: #f2f2f2;
}

button {
  padding: 5px 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

button:hover {
  background-color: #45a049;
}

.pagination {
  text-align: center;
  margin-bottom: 20px;
}

.pagination button {
  margin: 0 5px;
  padding: 5px 10px;
}

.modal {
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  width: 400px;
  text-align: center;
}

.close {
  float: right;
  font-size: 24px;
  cursor: pointer;
}
</style>
